#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <filesystem>
#include <cstdlib>

#include "lexer.hpp"

// 简单的命令行参数解析辅助函数
struct CommandLineOptions {
    std::string input_file;
    std::string output_file = "a.out";
    std::string target = "x86_64"; // 默认目标架构
    bool show_help = false;
    bool preprocess_only = false;
    bool compile_only = false;
    bool emit_asm = false;
};

void print_usage(const char* program_name) {
    std::cout << "Usage: " << program_name << " [options] <input.c>\n"
              << "Options:\n"
              << "  -o <file>        Specify output file (default: a.out)\n"
              << "  -target=<arch>   Set target architecture (e.g., x86_64, arm32)\n"
              << "  -S               Emit assembly only\n"
              << "  -c               Compile only, do not link\n"
              << "  -E               Preprocess only (not implemented yet)\n"
              << "  --help           Show this help message\n";
}

CommandLineOptions parse_command_line(int argc, char* argv[]) {
    CommandLineOptions opts;

    for (int i = 1; i < argc; ++i) {
        std::string arg = argv[i];

        if (arg == "--help") {
            opts.show_help = true;
        }
        else if (arg == "-o") {
            if (i + 1 >= argc) {
                std::cerr << "Error: -o requires an argument.\n";
                std::exit(1);
            }
            opts.output_file = argv[++i];
        }
        else if (arg.substr(0, 8) == "-target=") {
            opts.target = arg.substr(8);
        }
        else if (arg == "-S") {
            opts.emit_asm = true;
        }
        else if (arg == "-c") {
            opts.compile_only = true;
        }
        else if (arg == "-E") {
            opts.preprocess_only = true;
        }
        else if (arg[0] != '-') {
            if (!opts.input_file.empty()) {
                std::cerr << "Error: Multiple input files not supported yet.\n";
                std::exit(1);
            }
            opts.input_file = arg;
        }
        else {
            std::cerr << "Error: Unknown option '" << arg << "'\n";
            std::exit(1);
        }
    }

    return opts;
}

std::string read_source_file(const std::string& filename) {
    std::ifstream file(filename);
    if (!file.is_open()) {
        std::cerr << "Error: Cannot open file '" << filename << "'\n";
        std::exit(1);
    }

    if (!std::filesystem::exists(filename)) {
        std::cerr << "Error: File '" << filename << "' does not exist.\n";
        std::exit(1);
    }

    return std::string(
        (std::istreambuf_iterator<char>(file)),
        std::istreambuf_iterator<char>()
    );
}

// 前向声明：后续你将实现这些编译阶段
void run_preprocessor(const std::string& source, const CommandLineOptions& opts);
void run_compiler(const std::string& source, const CommandLineOptions& opts);
void run_assembler(const std::string& source, const CommandLineOptions& opts);
void run_linker(const CommandLineOptions& opts);

int main(int argc, char* argv[]) {
    if (argc < 2) {
        std::cerr << "Error: No input file specified.\n";
        print_usage(argv[0]);
        return 1;
    }

    auto opts = parse_command_line(argc, argv);

    if (opts.show_help) {
        print_usage(argv[0]);
        return 0;
    }

    if (opts.input_file.empty()) {
        std::cerr << "Error: Input file is required.\n";
        print_usage(argv[0]);
        return 1;
    }

    // 读取源文件内容
    std::string source_code = read_source_file(opts.input_file);

    // 根据选项执行不同阶段（目前为占位逻辑）
    if (opts.preprocess_only) {
        run_preprocessor(source_code, opts);
    } else if (opts.emit_asm) {
        run_assembler(source_code, opts);
    } else if (opts.compile_only) {
        run_compiler(source_code, opts);
    } else {
        // 完整编译流程（预处理 → 编译 → 汇编 → 链接）
        run_compiler(source_code, opts);
        run_linker(opts);
    }

    std::cout << "Compilation completed successfully.\n";
    return 0;
}

// 占位实现：后续替换为真实逻辑
void run_preprocessor(const std::string& /*source*/, const CommandLineOptions& /*opts*/) {
    std::cout << "[Preprocessor] Not implemented yet.\n";
}

void run_compiler(const std::string& source, const CommandLineOptions& opts) {
    std::cout << "[Compiler] Compiling for target: " << opts.target << "\n";
    // TODO: 调用词法分析、语法分析、代码生成等
    Lexer* lexer = Lexer::from_string(source);
    Token* token = lexer->next();
    while (token != nullptr) {
        token->print();
        token = lexer->next();
    }
}

void run_assembler(const std::string& /*source*/, const CommandLineOptions& opts) {
    std::cout << "[Assembler] Generating assembly for target: " << opts.target << "\n";
    // TODO: 输出 .s 文件
}

void run_linker(const CommandLineOptions& opts) {
    std::cout << "[Linker] Writing output to: " << opts.output_file << "\n";
    // TODO: 生成可执行文件或目标文件
}

